package code.lewdy.web.session;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

import com.lt.member.MemberService;

import code.lewdy.web.WebConstant;

/**
 * 监听Session Attribute，可用于监听登录用户变化 使用本类需要在web.xml中添加 <listener>
 * <listener-class>code
 * .lewdy.web.session.HttpSessionAttributeListenerImpl</listener-class>
 * </listener>
 * 
 * @author liuding,2012-4-25
 * 
 *         $LastChangedDate$ $Author$
 */
public class HttpSessionAttributeListenerImpl implements
		HttpSessionAttributeListener {
	// 登录用户的ID
	private static List<Integer> sessionUserIds = new ArrayList<Integer>();

	public static List<Integer> getSessionUserIds() {
		for (int i = 0; i < sessionUserIds.size(); i++) {
			System.out.println("sessionId" + i + ":" + sessionUserIds.get(i));
		}
		return sessionUserIds;
	}

	public void attributeAdded(HttpSessionBindingEvent se) {
		// TODO Auto-generated method stub
		if (WebConstant.SESSION_USER_ID.equals(se.getName())) {
			if (!sessionUserIds.contains((Integer) se.getValue())){
				sessionUserIds.add((Integer) se.getValue());
				MemberService.setLoginFlag((Integer) se.getValue());
				System.out.println("登录用户id:" + (Integer) se.getValue());
			}
		}
	}

	public void attributeRemoved(HttpSessionBindingEvent se) {
		// TODO Auto-generated method stub
		if (WebConstant.SESSION_USER_ID.equals(se.getName())) {
			if (sessionUserIds.contains((Integer) se.getValue()))
				sessionUserIds.remove((Integer) se.getValue());
				MemberService.setLogoutFlag((Integer) se.getValue());
				System.out.println("退出登录用户id:" + (Integer) se.getValue());
		}
	}

	public void attributeReplaced(HttpSessionBindingEvent se) {
		// TODO Auto-generated method stub
		/*: java.lang.String cannot be cast to java.lang.Integer 
		 * 当session value为字符串时不能执行下面的代码：出异常
		 * */
		System.out.println("Session attributeReplaced=>" + se.getName()+":"+se.getValue());
		if(se.getName().equals(WebConstant.SESSION_USER_ID)){
			if (sessionUserIds.contains((Integer) se.getValue()))
				sessionUserIds.remove((Integer) se.getValue());
			sessionUserIds.add((Integer) se.getSession().getAttribute(
					WebConstant.SESSION_USER_ID));
		}
		/*
		if (sessionUserIds.contains((Integer) se.getValue()))
			sessionUserIds.remove((Integer) se.getValue());
		sessionUserIds.add((Integer) se.getSession().getAttribute(
				WebConstant.SESSION_USER_ID));
		System.out.println("Session new:"
				+ (Integer) se.getSession().getAttribute(
						WebConstant.SESSION_USER_ID));
*/	}

}
